package our.pack;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MediaAudioSaveActivity extends Activity{
	
	private Button save, discard;
	private EditText editName;
	private String fileName;
	private MetaDataDataSource metaDataDataSource;
	private MyPoint point;
	
	/**
	 * saves the audio file you made in MediaAudioActivity
	 */
	public void onCreate(Bundle SaveInstanceState){
		super.onCreate(SaveInstanceState);
		setContentView(R.layout.media_audio_save);
		
		//db
		metaDataDataSource = new MetaDataDataSource(this);
		metaDataDataSource.open();
		
		//get the point where it's made
		Intent i = this.getIntent();
		Bundle b = i.getExtras();
		fileName = b.getString("PATH");
		point = (MyPoint) b.get("Point");
		
		
		save = (Button) findViewById(R.id.btnSaveAudio);
		discard = (Button) findViewById(R.id.btnDiscardAudio);
		editName = (EditText) findViewById(R.id.editAudioName);
		
		//if people click the discard the file get deleted
		discard.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				//delete the file
				File file = new File(fileName);
				file.delete();
				finish();
			}
		});
		
		//saves the file
		save.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				File file = new File(fileName);
				File newFile = new File(Environment.getExternalStorageDirectory() + "/" + editName.getText().toString() + ".3GP");
				Log.d("Audio", "newFileName: "  + newFile);
				boolean itWorked = file.renameTo(newFile);
				if(itWorked == false){
					Toast.makeText(getApplicationContext(), "It didn't work", Toast.LENGTH_LONG);
				}
				
				String[] ids = TimeZone.getAvailableIDs(+1 * 60 * 60 * 1000);					
				SimpleTimeZone cest = new SimpleTimeZone(+1 * 60 * 60 * 1000, ids[0]);
				Calendar cal = new GregorianCalendar(cest);
				String date = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1)  + "-" + cal.get(Calendar.YEAR);
				
				//saves it in the database
				MetaData m = metaDataDataSource.createMetaData(editName.getText().toString(), Environment.getExternalStorageDirectory() + "/" + editName.getText().toString() + ".3GP", date, "audio", point);
				
				
				finish();
			}
		});
		
	}

}
